package ink.xiaobaibai.service.monthly.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.common.AddDayStatus;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.RoleEvents;
import ink.xiaobaibai.common.ServiceResult;
import ink.xiaobaibai.entity.MonthlyAddDay;
import ink.xiaobaibai.entity.MonthlyfeeOrder;
import ink.xiaobaibai.enumOxy.MonthlyfeeOrderStatus;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IMonthlyAddDayService;
import ink.xiaobaibai.service.IMonthlyfeeOrderService;
import ink.xiaobaibai.service.monthly.IOrderAddDayService;
import ink.xiaobaibai.serviceOxy.ISmsService;
import ink.xiaobaibai.units.MySecurity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: 月费订单延长服务
 * @author: 小白白
 * @create: 2021-06-09
 **/

@Service
@Slf4j
public class OrderAddDayServiceImpl implements IOrderAddDayService {

    @Autowired
    private IMonthlyfeeOrderService orderService;

    @Autowired
    private IMonthlyAddDayService addDayService;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private ISmsService smsService;

    @Override
    public Page<MonthlyAddDay> getAddDayListAllRole(Integer pageNum, Integer pageSize) {
        Integer userId = MySecurity.getUserId();
        String role = MySecurity.getRole();
        QueryWrapper<MonthlyAddDay> q1 = new QueryWrapper<>();
        if (!MySecurity.isPower(MyRole.POWER_MONTHLY)) {
            RoleEvents<QueryWrapper<MonthlyAddDay>> roleEvents = new RoleEvents<>(role);
            roleEvents
                    .distributor(() -> {
                        q1.eq("admin_user_id", userId);
                        return q1;
                    })
                    .agent(() -> {
                        Integer depId = this.adminUserService.getDepId(userId);
                        q1.eq("dep_id", depId);
                        return q1;
                    })
                    .oa(() -> q1)
                    .execute();
        }
        q1.orderByDesc("create_time");
        Page<MonthlyAddDay> page = this.addDayService.page(new Page<>(pageNum, pageSize), q1);
        return page;
    }

    @Override
    public ServiceResult addOrderDay(String orderId, Integer day, String reason) {
        QueryWrapper<MonthlyfeeOrder> q1 = new QueryWrapper<>();
        q1.select("admin_user_id", "status", "expire_time", "admin_dep_id");
        q1.eq("order_id", orderId);
        MonthlyfeeOrder order = this.orderService.getOne(q1);
        //检验状态
        if (order == null) {
            return ServiceResult.fail("当前订单不存在");
        }
        if (!order.getStatus().equals(MonthlyfeeOrderStatus.INUSE.getStatus())) {
            return ServiceResult.fail("当前订单状态为:" + order.getStatus() + ",不可操作");
        }
        if (!MySecurity.isPower(MyRole.POWER_MONTHLY) && !order.getAdminUserId().equals(MySecurity.getUserId())) {
            return ServiceResult.fail("不可操作他人订单");
        }
        if (order.getExpireTime().getTime() < System.currentTimeMillis()) {
            return ServiceResult.fail("当前月费已过期,不可申请");
        }
        MonthlyAddDay monthlyAddDay = new MonthlyAddDay(orderId, day, reason, MySecurity.getUserId(),
                this.adminUserService.getDepId(MySecurity.getUserId()), null);
        String role = MySecurity.getRole();
        if (role.equals(MyRole.ADMIN) || role.equals(MyRole.POWER_MONTHLY)) {
            // 直接ok
            monthlyAddDay.setStatus(AddDayStatus.ADMIN.getStatus());
            this.addDayService.save(monthlyAddDay);
            this.doByAdmin(monthlyAddDay.getId(), true);
        } else if (role.equals(MyRole.AGENT)) {
            monthlyAddDay.setStatus(AddDayStatus.ADMIN.getStatus());
            this.addDayService.save(monthlyAddDay);
            // 发给管理
            this.smsService.addDay(-1);
        } else {
            monthlyAddDay.setStatus(AddDayStatus.AGENT.getStatus());
            this.addDayService.save(monthlyAddDay);
            // 发送给经理
            this.smsService.addDay(order.getAdminDepId());
        }
        return ServiceResult.ok();
    }

    @Override
    public ServiceResult agreeAddDayByAgent(Integer id) {
        return this.doByAgent(id, true);
    }

    @Override
    public ServiceResult refuseAddDayByAgent(Integer id) {
        return this.doByAgent(id, false);
    }

    @Override
    public ServiceResult agreeAddDayByAdmin(Integer id) {
        return this.doByAdmin(id, true);
    }

    @Override
    public ServiceResult refuseAddDayByAdmin(Integer id) {
        return this.doByAdmin(id, false);
    }

    private ServiceResult doByAgent(Integer id, boolean agree) {
        MonthlyAddDay monthlyAddDay = this.addDayService.getById(id);
        if (monthlyAddDay == null) {
            return ServiceResult.fail("当前数据不存在");
        }
        if (!monthlyAddDay.getDepId().equals(this.adminUserService.getDepId(MySecurity.getUserId()))) {
            return ServiceResult.fail("不可批准其他部门的延长申请");
        }
        if (!monthlyAddDay.getStatus().equals(AddDayStatus.AGENT.getStatus())) {
            return ServiceResult.fail("当前状态为:" + monthlyAddDay.getStatus() + ",不可操作");
        }
        UpdateWrapper<MonthlyAddDay> u1 = new UpdateWrapper<>();
        u1.set("status", agree ? AddDayStatus.ADMIN.getStatus() : AddDayStatus.NO.getStatus());
        u1.eq("id", id);
        if (agree) {
            this.smsService.addDay(-1);
        }
        return this.addDayService.update(u1) ? ServiceResult.ok() : ServiceResult.fail("未知错误");
    }

    private ServiceResult doByAdmin(Integer id, boolean agree) {
        MonthlyAddDay monthlyAddDay = this.addDayService.getById(id);
        if (!monthlyAddDay.getStatus().equals(AddDayStatus.ADMIN.getStatus())) {
            return ServiceResult.fail("当前状态为:" + monthlyAddDay.getStatus() + ",不可批准");
        }
        UpdateWrapper<MonthlyAddDay> u1 = new UpdateWrapper<>();
        u1.set("status", AddDayStatus.OK.getStatus());
        u1.eq("id", id);
        this.addDayService.update(u1);
        if (agree) {
            //订单是否已经过期,或者订单状态已经转移
            String orderId = monthlyAddDay.getOrderId();
            MonthlyfeeOrder order = this.orderService.getById(orderId);
            if (order == null) {
                return ServiceResult.fail("订单不存在");
            }
            if (!order.getStatus().equals(MonthlyfeeOrderStatus.INUSE.getStatus())) {
                return ServiceResult.fail("失败,当前订单状态为:" + order.getStatus());
            }
            if (order.getExpireTime().getTime() < System.currentTimeMillis()) {
                return ServiceResult.fail("失败,当前订单已经过期,失效时间:" + order.getExpireTime());
            }
            //去修改对应的有效期
            Integer day = monthlyAddDay.getDay();
            //增加延长天数
            order.setExtendedDay(order.getExtendedDay() + day);
            //增加失效时间
            order.setExpireTime(DateUtils.addDays(order.getExpireTime(), day));
            this.orderService.updateById(order);
            return ServiceResult.ok();
        } else {
            UpdateWrapper<MonthlyAddDay> u2 = new UpdateWrapper<>();
            u2.set("status", AddDayStatus.NO.getStatus());
            u2.eq("id", id);
            return this.addDayService.update(u2) ? ServiceResult.ok() : ServiceResult.fail("未知错误");
        }

    }

}
